package com.zht.service.Impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zht.config.OssConfig;
import com.zht.service.OssService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Resource
    private OssConfig ossConfig;
    @Override
    public String upload(MultipartFile file) {
        if (file != null){
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + suffix;
            log.info("新文件名:{}", newFileName);

            //读取文件
            String endPoint = ossConfig.getEndPoint();
            String bucket = ossConfig.getBucket();
            String accessKey = ossConfig.getAccessKey();
            String secretKey = ossConfig.getSecretKey();
            String dir = ossConfig.getDir();

            OSS ossClient = new OSSClientBuilder().build(endPoint,accessKey,secretKey);
            String uploadPath = dir + newFileName;
            InputStream inputStream;
            try{
                inputStream = file.getInputStream();
            }catch (IOException e){
                throw new RuntimeException(e);
            }

            ossClient.putObject(bucket,uploadPath,inputStream);

            ossClient.shutdown();

            return "https://" + bucket + "." + endPoint + "/" + uploadPath;
        }else {
            return "上传失败";
        }
    }
}
